package com.echoesnet.echoesshortvideo.Fragments;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.Activities.PlayVideoActivity;
import com.echoesnet.echoesshortvideo.Beans.FansFocusBean;
import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.Constant.EsvConstant;
import com.echoesnet.echoesshortvideo.Persistence.MyVideosInfoEntity;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.ListOfMyVideoViewModel;
import com.echoesnet.echoesshortvideo.views.adapters.MyVideoListAdapter;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.ui.emptyview.emptyViewOnShownListener;
import com.orhanobut.logger.Logger;
import com.shizhefei.fragment.LazyFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyVideoListFrg extends LazyFragment
{
    private final String TAG = MyVideoListFrg.class.getSimpleName();

    public static final String INTENT_STRING_TABNAME = "intent_String_tabName";
    public static final String INTENT_INT_POSITION = "intent_int_position";

    private Activity mActivity;
    private ListOfMyVideoViewModel viewModel;
    private UltimateRecyclerView urvList;
    private MyVideoListAdapter mListAdapter;
    private TextView infoProductNum;
    private int iStart = 0;
    private final int iStep = 10;

    private List<MyVideosInfoEntity> mList;
    private MyBroadCast receiver;

    private String uId;
    private String num;


    @Override
    protected View getPreviewLayout(LayoutInflater inflater, ViewGroup container)
    {
        return inflater.inflate(R.layout.layout_preview, container, false);
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState)
    {
        super.onCreateViewLazy(savedInstanceState);
        mActivity = getActivity();
        setContentView(R.layout.frg_tab_my);
        urvList = (UltimateRecyclerView) findViewById(R.id.urvMyVideoList);
        infoProductNum = (TextView) findViewById(R.id.infoProductNum);
        //================修改代码=-=============
        mList = new ArrayList<>();
        setList();

        viewModel = ViewModelProviders.of(MyVideoListFrg.this).get(ListOfMyVideoViewModel.class);
        Bundle bundle = getArguments();
        if (bundle != null)
        {
            uId = bundle.getString("uId", "");
        }

        viewModel.getMyVideosList().observe(this, new Observer<Map<String, Object>>()
        {
            @Override
            public void onChanged(@Nullable Map<String, Object> map)
            {

                boolean isRefresh = (boolean) map.get("isRefresh");
                String totalNum = (String) map.get("totalNum");
                infoProductNum.setText(totalNum);
                Logger.t(TAG).d("getMyVideosList:走了,totalNum==" + totalNum);
                List<MyVideosInfoEntity> list = (List<MyVideosInfoEntity>) map.get("videoList");
                if (isRefresh)
                {
                    mList.clear();
                }
                // 添加去重复 ====
                for (MyVideosInfoEntity fansBean : list)
                {
                    if (mList.contains(fansBean))
                    {
                        int index = mList.indexOf(fansBean);
                        mList.remove(index);
                    }
                    mList.add(fansBean);
                }

                urvList.setRefreshing(false);
                mListAdapter.notifyDataSetChanged();
                if (mList != null)
                {
                    //     setupList(list);
                    if (mList.isEmpty() && list.isEmpty())
                    {
                        urvList.showEmptyView();
                    }
                    else
                    {
                        urvList.hideEmptyView();
                    }

                }
            }
        });

        viewModel.getCheckVideoResult().observe(this, result -> {

            if (result != null)
            {
                if ("0".equals(result.get("result")))
                {
                    Intent intent = new Intent(mActivity, PlayVideoActivity.class);
                    intent.putExtra("videoId", result.get("videoId"));
                    intent.putExtra("toUserId", result.get("toUserId"));
                    intent.putExtra("openSource", result.get("openSource"));
                    startActivity(intent);
                    mActivity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                }
                else
                {
                    ToastUtils.showShort("该视频已被删除");
                }
            }
        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(EsvConstant.ACTION_NOTIFY_MY_VIDEO_NUM);
        intentFilter.addAction(CommonConstant.REQUEST_LOGIN_CODE);
        receiver = new MyBroadCast();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, intentFilter);



        if (TextUtils.isEmpty(uId))
            viewModel.requestMyVideosList(iStart, iStep, false);
    }

    public void  requestMyVideosList(String uId)
    {
        this.uId= uId;
        if(mList!=null)
            mList.clear();
        iStart = 0;
        viewModel.requestVideosList(uId, iStart, iStep, false);
    }

    private class MyBroadCast extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            switch (intent.getAction())
            {
                case EsvConstant.ACTION_NOTIFY_MY_VIDEO_NUM:
                case CommonConstant.REQUEST_LOGIN_CODE:
                    refreshVideoList(uId);
                    break;
                default:
                    break;
            }
        }
    }

    private void setList()
    {
        mListAdapter = new MyVideoListAdapter(mActivity, mList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2)
        {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state)
            {
                return 300;
            }
        };
        urvList.setLayoutManager(gridLayoutManager);
        urvList.reenableLoadmore();
        urvList.setHasFixedSize(false);
        urvList.hideEmptyView();

        urvList.setEmptyView(R.layout.my_video_empty_view, UltimateRecyclerView.EMPTY_CLEAR_ALL, new emptyViewOnShownListener()
        {
            @Override
            public void onEmptyViewShow(View mView)
            {
                String des = "";
                if (!TextUtils.isEmpty(uId))
                {
                    des = "Ta还没有发布作品呦~";
                }
                else
                {
                    des = "您还没有发布作品呦，快去发布吧~";
                }
                ((TextView) mView.findViewById(R.id.tvDesc)).setText(des);
            }
        });
        mListAdapter.setCustomLoadMoreView(LayoutInflater.from(mActivity).inflate(R.layout.bottom_progressbar, null));
        urvList.setAdapter(mListAdapter);
        urvList.setOnLoadMoreListener((itemsCount, maxLastVisiblePosition) -> {
            iStart += iStep;
            if (!TextUtils.isEmpty(uId))
            {
                viewModel.requestVideosList(uId, iStart, iStep, false);
            }
            else
            {
                viewModel.requestMyVideosList(iStart, iStep, false);
            }

        });

        urvList.setDefaultOnRefreshListener(() -> {
            iStart = 0;
            if (!TextUtils.isEmpty(uId))
            {
                viewModel.requestVideosList(uId, iStart, iStep, true);
            }
            else
            {
                viewModel.requestMyVideosList(iStart, iStep, true);
            }
        });
        mListAdapter.setOnItemClickListener((view, infoEntity) -> {
            String a = "";
            switch (view.getId())
            {
//                case R.id.tvNickName:
//                    a = "R.id.tvNickName";
//                    break;
//                case R.id.ivAvatarLeft:
//                    a = "R.id.ivAvatar";
//                    break;
                case R.id.ivCoverImg:
                    a = "R.id.ivCoverImg";
                    viewModel.checkVideoState(infoEntity.getVideoId(), infoEntity.getUserId(), "1");
                    break;
            }
        });
    }

    public static MyVideoListFrg newVideoListFrg(@Nullable String uId)
    {
        Bundle bundle = new Bundle();
        bundle.putString("uId", uId);
        MyVideoListFrg frg = new MyVideoListFrg();
        frg.setArguments(bundle);
        return frg;
    }


    @Override
    protected void onDestroyViewLazy()
    {
        super.onDestroyViewLazy();
        if (receiver != null)
            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
    }

    public void setupList(List<MyVideosInfoEntity> list)
    {
        if (null == mListAdapter)
        {
            mListAdapter = new MyVideoListAdapter(mActivity, list);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2)
            {
                @Override
                protected int getExtraLayoutSpace(RecyclerView.State state)
                {
                    return 300;
                }
            };

            urvList.setLayoutManager(gridLayoutManager);
            urvList.reenableLoadmore();
            urvList.setHasFixedSize(false);
            urvList.setEmptyView(R.layout.my_video_empty_view, UltimateRecyclerView.EMPTY_CLEAR_ALL, new emptyViewOnShownListener()
            {
                @Override
                public void onEmptyViewShow(View mView)
                {

                }
            });
            mListAdapter.setCustomLoadMoreView(LayoutInflater.from(mActivity).inflate(R.layout.bottom_progressbar, null));
//            urvList.setLoadMoreView(LayoutInflater.from(mActivity).inflate(R.layout.bottom_progressbar, null));
            urvList.setAdapter(mListAdapter);

            urvList.disableLoadmore();


            urvList.setOnLoadMoreListener((itemsCount, maxLastVisiblePosition) -> {
                iStart += iStep;
                if (!TextUtils.isEmpty(uId))
                {
                    viewModel.requestVideosList(uId, iStart, iStep, false);
                }
                else
                {
                    viewModel.requestMyVideosList(iStart, iStep, false);
                }

            });

            urvList.setDefaultOnRefreshListener(() -> {
                iStart = 0;
                if (!TextUtils.isEmpty(uId))
                {
                    viewModel.requestVideosList(uId, iStart, iStep, true);
                }
                else
                {
                    viewModel.requestMyVideosList(iStart, iStep, true);
                }
            });


            registerForContextMenu(urvList);

        }
        else
        {
            mListAdapter.setDataList(list);
        }
        mListAdapter.notifyDataSetChanged();
    }

    /**
     * @param tUid 要查看用户的uid，如果是自己就传入null
     */
    public void refreshVideoList(String tUid)
    {
        iStart = 0;
        if (!TextUtils.isEmpty(tUid))
        {
            viewModel.requestVideosList(tUid, iStart, iStep, true);
        }
        else
        {
            viewModel.requestMyVideosList(iStart, iStep, true);
        }
    }


}